<template>
  <section>
    <div>
<!--      <canvas v-show="isWatching" id="myChart"></canvas>-->
            <canvas id="myChart"></canvas>
    </div>
  </section>
</template>

<script>
import F2 from "@antv/f2";
import dayjs from "dayjs";
import {Button} from "vant";
import common from "../../util/index";
// eslint-disable-next-line no-unused-vars
import {mapState, mapGetters, mapMutations, mapActions} from "vuex";

export default {

  computed: {
    ...mapState(["isRecording", "isWatching"]),
  },
  watch: {
    isRecording: function (newValue, oldValue) {
      if (!this.isInitChart) {
        this.isInitChart = true;
        this.initChart();
      }
      if (oldValue !== newValue) {
        console.log("newRecording", newValue);
        this.isRendered = newValue == 1;
      }
    },
    isRendered: function (newValue, oldValue) {
      if (oldValue !== newValue) {
        console.log("newRendered", newValue);
        if (newValue === false) {
          clearInterval(this.interval);
          this.interval = null;
        } else {
          this.interval = setInterval(() => {
            this.renderData();
          }, 2000);
        }
      }
    },
  },
  components: {[Button.name]: Button},
  data() {
    return {
      isRendered: false,
      isInitChart: false,
      chart: null,
      datas: [],
      interval: null,
      displayMax: 30,
    };
  },
  mounted() {
    resize_canvas(null,400);
    this.initChart();
  },
  methods: {
    initChart() {
      F2.Animate.registerAnimation("lineUpdate", function (updateShape, animateCfg) {
        const cacheShape = updateShape.get("cacheShape"); // 该动画 shape 的前一个状态
        const cacheAttrs = cacheShape.attrs; // 上一个 shape 属性
        const oldPoints = cacheAttrs.points; // 上一个状态的关键点
        const newPoints = updateShape.attr("points"); // 当前 shape 的关键点

        const oldLength = oldPoints.length;
        const newLength = newPoints.length;
        const deltaLength = newLength - oldLength;

        const lastPoint = newPoints[newPoints.length - 1];
        for (let i = 0; i < deltaLength; i++) {
          oldPoints.push(lastPoint);
        }

        updateShape.attr(cacheAttrs);
        updateShape.animate().to({
          attrs: {
            points: newPoints,
          },
          duration: 800,
          easing: animateCfg.easing,
        });
      });

      // 添加数据，模拟数据，可以指定当前时间的偏移的秒
      this.chart = new F2.Chart({
        id: "myChart",
        pixelRatio: window.devicePixelRatio,
      });
      const defs = {
        time: {
          type: "timeCat",
          mask: "mm:ss",
          range: [0, 1],
          tickCount: 8,
          isRounding: true,
        },
        value: {
          type: "linear",
          sortable: true,
          nice:true,
          tickCount: 16,
          formatter: val => parseFloat(val).toFixed(2),
        },
      };
      this.chart.source(this.datas, defs);

      this.chart.tooltip({
        custom: true,
        showXTip: true,
        showYTip: true,
        snap: true,
        crosshairsType: "xy",
        crosshairsStyle: {
          lineDash: [2],
        },
      });
      this.chart.axis("time", {
        label: function (text, index, total) {
          const textCfg = {
            text: text,
          };
          return textCfg;
        },
        grid: null,
      });
      this.chart.axis("value", {
        label: function (text, index, total) {
          var number = parseFloat(text);
          var textCfg = {
            text: number,
          };
          if (number > 37.5) {
            textCfg.text = text;
            textCfg.fill = "#F5222D";
          } else if (number <= 35.5) {
            textCfg.text = text;
            textCfg.fill = "#52C41A";
          }
          return textCfg;
        },
      });

      this.chart.line().position("time*value").animate({
        update: {
          animation: "lineUpdate",
        },
      });

      this.chart.render();
      // this.isInitChart = true;
    },
    renderData() {
      let dt = this.getData();
      this.chart.changeData(dt);
    },
    getData() {

      const day = dayjs().format("YYYY-MM-DD");
      const filename = "cache://blewendu_" + day + ".log";
      const originalData = this.readFileSync(filename);
      return originalData.length === 0 ? [] : originalData.slice(1).split("@").slice(-parseInt(this.displayMax)).map(val => ({
        time: dayjs(day + " " + val.split(" ")[0]).valueOf(),
        value: val.split(" ")[1],
      }));

    },
    ...common.methods,
  },
};


function resize_canvas(width = null, height = null) {
  var canvas = document.getElementById("myChart");
  if (canvas.width < window.innerWidth) {
    canvas.width = width || window.innerWidth;
  }

  if (canvas.height < window.innerHeight) {
    canvas.height = height || window.innerHeight;
  }
}

</script>

<style lang="scss">
  @import "../../assets/style/var.scss";
</style>
